import Taro, { Component } from "@tarojs/taro";
import { View } from "@tarojs/components";
import {
  AtCalendar,
  AtTimeline,
  AtInput,
  AtSwitch,
  AtButton,
  AtDivider,
  AtIcon
} from "taro-ui";
import { connect } from "@tarojs/redux";
import dayjs from "dayjs";

import {
  onAddMission,
  onPopMission,
  onSubmitPlan,
  onSubmitPlanSuccess
} from "../../actions/makePlan";
import { onCheckTodayPlan } from "../../actions/checkPlan";

@connect(
  state => state,
  {
    onAddMission,
    onPopMission,
    onSubmitPlan,
    onSubmitPlanSuccess,
    onCheckTodayPlan
  }
)
class DayPlan extends Component {
  constructor() {
    super(...arguments);
    const today = new Date(),
      todayFormat = `${today.getFullYear()}-${today.getMonth() +
        1}-${today.getDate()}`,
      calSelectedDays = {
        value: {
          start: todayFormat,
          end: todayFormat
        }
      };
    this.state = {
      defaultSelectedDays: new Date(),
      selectedDays: calSelectedDays,
      planMoreDay: false,
      setSelectedDays: false,
      planName: ""
    };
  }

  onInputPlanName = v => {
    this.setState({
      planName: v
    });
  };

  onSelectDays = value => {
    this.setState({
      selectedDays: value,
      setSelectedDays: value.value.end ? true : false
    });
  };

  changePlanMoreDay = v => {
    this.setState(prevState => ({
      planMoreDay: v,
      selectedDays: v ? null : prevState.defaultSelectedDays,
      setSelectedDays: false
    }));
  };

  clickToResetDays() {
    this.state.setSelectedDays
      ? this.setState({ setSelectedDays: false })
      : null;
  }

  onDeleteMission = () => {
    this.props.makePlan.submitedMission.length === 0
      ? Taro.atMessage({
          message: "任务列表为空哦！",
          type: "error",
          duration:3000
        })
      : this.props.onPopMission();
  };

  onResetPlan = () => {
    this.setState({
      setSelectedDays: false,
      planName: ""
    });
  };

  onSubmitPlan = () => {
    this.props.makePlan.submitedMission.length === 0
      ? Taro.atMessage({
          message: "未添加任何小任务！",
          type: "error",
          duration:3000
        })
      : !this.state.setSelectedDays
      ? Taro.atMessage({
          message: "请选择计划生效日期",
          type: "error",
          duration:3000
        })
      : this.props.onSubmitPlan({
          user: this.props.user.openid,
          day: dayjs(new Date()).format("YYYY年MM月DD日 HH:mm"),
          planName: this.state.planName !== "" ? this.state.planName : "匿名",
          selectedDays: this.state.selectedDays,
          missions: this.props.makePlan.submitedMission
        });
  };

  onCheckFinishedPlans() {
    Taro.redirectTo({
      url: `/pages/FinishedPlan/finishedPlan?user=${
        this.props.user.openid
      }&days=`
    });
  }

  freshPlan() {
    let today = new Date(),
      data = {
        user: this.props.user.openid,
        days: [
          dayjs(
            `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`
          ).format("YYYY-MM-DD")
        ]
      };
    this.props.onCheckTodayPlan(data);
  }

  render() {
    {
      this.props.makePlan.submitedPlan ? this.onResetPlan() : null;
    }
    const timelineItems = this.props.makePlan.submitedMission.map(v => {
      let contentArr = v.missionDetails.split("\n");
      contentArr.unshift(`${v.startTime} ~ ${v.endTime}`);
      return {
        title: v.missionName,
        content: contentArr
      };
    });
    this.props.makePlan.submitedPlan
      ? (Taro.atMessage({
          message: this.props.user.specialWords.length===0?"制定计划成功":this.props.user.specialWords[4],
          info: "info",
          duration:3000
        }),
        this.props.onSubmitPlanSuccess(),
        this.freshPlan())
      : null;
    return (
      <View>
        <AtInput
          title='计划名称'
          type='text'
          placeholder='默认为匿名'
          value={this.state.planName}
          onChange={this.onInputPlanName}
        />
        <AtSwitch
          title='计划多天'
          checked={this.state.planMoreDay}
          onChange={this.changePlanMoreDay}
        />
        <AtButton type='secondary' full onClick={this.clickToResetDays}>
          {!this.state.setSelectedDays
            ? "请选择时间："
            : this.state.planMoreDay
            ? `已选择：${this.state.selectedDays.value.start}~${
                this.state.selectedDays.value.end
              }，点此重新选择`
            : `已选择：${this.state.selectedDays.value.start}，点此重新选择`}
        </AtButton>
        {this.state.setSelectedDays ? null : (
          <AtCalendar
            isSwiper
            isMultiSelect={this.state.planMoreDay}
            onSelectDate={this.onSelectDays}
          />
        )}
        <AtDivider content='已添加的小任务' />
        <AtTimeline items={timelineItems} />
        <AtIcon
          value='add-circle'
          size='60'
          color='#90B1EF'
          onClick={this.props.onAddMission}
        />
        <AtIcon
          value='subtract-circle'
          size='60'
          color='#90B1EF'
          onClick={this.onDeleteMission}
        />
        <AtButton
          full
          type='primary'
          className='submit-plan'
          onClick={() => {
            this.onSubmitPlan(this.state);
          }}
        >
          提交计划
        </AtButton>
        <AtButton full type='secondary' onClick={this.onCheckFinishedPlans}>
          查看已制定的计划
        </AtButton>
      </View>
    );
  }
}

export default DayPlan;
